import Search from "antd/es/input/Search";
import { useEffect, useState, type ChangeEvent } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { LIST_SEARCH_PARAM_KEY } from "../constant";

export default function ListSearch() {
  const [value, setValue] = useState("");
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();
  useEffect(() => {
    const newVal = searchParams.get(LIST_SEARCH_PARAM_KEY);
    setValue(newVal || "");
  }, [searchParams]);
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value);
  }
  function handleSearch(value: string) {
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value}`,
    });
  }
  return (
    <Search
      placeholder="输入关键字"
      allowClear
      value={value}
      onSearch={handleSearch}
      onChange={handleChange}
      style={{ width: "260px" }}
    ></Search>
  );
}
